//
//  QueryViewController.m
//  Rich
//
//  Created by Kenny Chen on 13/8/29.
//  Copyright (c) 2013年 Kenny Chen. All rights reserved.
//
// TODO: Add 'Query Button'
//

#import "QueryViewController.h"

@interface QueryViewController ()

@end

@implementation QueryViewController

@synthesize queryTransactions;
@synthesize defaultQueryCondition;

- (id)initWithStyle:(UITableViewStyle)style
{
    self = [super initWithStyle:style];
    if (self) {
        self.tableView.tag = RichTableViewTagQuery;
        self.mode = RichTableModeListReadonly;
        dateCondition = ByDay;
        beginDate = [[DateHelper dateFor:RichDateToday byDate:nil] copy];
        endDate = [[DateHelper dateFor:RichDateToday byDate:nil] copy];
        defaultPickerTitles = [[NSMutableArray alloc] initWithObjects:
                                RichLocaleString(@"By Day"),
                                RichLocaleString(@"By Month"), nil];
        defaultQueryCondition = nil;
        queryTransactions = [[NSMutableArray alloc] init];
    }
    
    return self;
}

- (void)initFormatableDatePicker
{
    beginDatePicker = [[FormatableDatePicker alloc] init];
    beginDatePicker.date = [NSDate date];
    
    endDatePicker = [[FormatableDatePicker alloc] init];
    endDatePicker.date = [NSDate date];
}

- (void)viewDidLoad
{
    [super viewDidLoad];

    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
 
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    if (self.mode == RichTableModeListEditable) {
        [self initDatePicker];
        [self initFormatableDatePicker];
        [self initDefaultPicker];
        [self initInputToolbar:RichInputToolbarButtonDefaultSet];
    }
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [self loadSearchResult:defaultQueryCondition];
    
    [self.tableView reloadData];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSString *)dateConditionString
{
   return [NSString stringWithFormat:@"date >= \"%@\" and date < \"%@\"",
            [[RichDelegate core] stringFromDate:beginDate format:@"yyyy-MM-dd"],
            [[RichDelegate core] stringFromDate:endDate format:@"yyyy-MM-dd"]];
}

- (void)loadTransactions:(NSMutableArray *)transactions condition:(NSString *)condition
{
    if (condition == nil)
        condition = defaultQueryCondition;
    
    [[RichDelegate core] loadGeneralTransactions:transactions
                                        category:RootCategoryAll
                                           where:condition
                                    beginAtIndex:0
                                           limit:0
                                      descending:YES];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [super numberOfSectionsInTableView:tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.mode == RichTableModeListReadonly || section == 1)
        return [queryTransactions count];
    else if (section == 0)
        return 3;
    
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *code;
    UITableViewCell *cell = nil;
    RichTableViewTextfieldCell *textfieldCell = nil;
    
    if (self.mode == RichTableModeListReadonly || [indexPath section] == 1) {
        tableCellStyle = RichTableCellStyleDetail;
        cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        RichTransactionGeneral *trans = [queryTransactions objectAtIndex:[indexPath row]];
        
        if (trans) {
            code = [[[RichDelegate core] accounts:accounts findAccountByID:trans.accountFrom] currencyCode];
            
            cell.textLabel.text = [NSString stringWithFormat:@"%@ %@ - %@ %@",
                                   [[RichDelegate core] stringFromDate:trans.date format:@"MM/dd"],
                                   [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:[[RichDelegate core] rootCategoryOf:trans.categoryCode]]],
                                   [[[RichDelegate core] category] objectForKey:[NSNumber numberWithUnsignedInteger:trans.categoryCode]],
                                   trans.installmentPaymentTimes > 1 ?
                                   [NSString stringWithFormat:@"(%lu/%lu)", trans.installmentMade, trans.installmentPaymentTimes] : @""];
            
            if (trans.installmentMade == 1)
                cell.detailTextLabel.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:code], trans.installmentDownPayment];
            else {
                float rate = trans.installmentRate;
                
                cell.detailTextLabel.text = [NSString stringWithFormat:[[RichDelegate core] currencyDecimalFormatString:code],
                                             trans.amount + ((int)(((trans.amount * trans.installmentPaymentTimes) - trans.installmentDownPayment) * rate) / 100)];
            }
            
            if (self.callerDelegate)
                cell.accessoryType = UITableViewCellAccessoryNone;
            else
                cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            cell.userInteractionEnabled = YES;
        }
    }
    else if ([indexPath section] == 0) {
        tableCellStyle = RichTableCellStyleTextfield;
        textfieldCell = (RichTableViewTextfieldCell *)[super tableView:tableView cellForRowAtIndexPath:indexPath];
        
        cell = textfieldCell;
        
        if ([indexPath row] == 0) {
            textfieldCell.textLabel.text = RichLocaleString(@"Query Type");
            textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
            textfieldCell.textfield.inputView = defaultPicker;
            textfieldCell.textfield.text = [defaultPickerTitles objectAtIndex:dateCondition];
        }
        else {
            switch (dateCondition) {
                case ByDay:
                    if ([indexPath row] == 1) {
                        textfieldCell.textLabel.text = RichLocaleString(@"Begin Date");
                        textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                        textfieldCell.textfield.inputView = beginDatePicker;
                        textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:beginDatePicker.date format:RichLocaleString(@"yyyy-MM-dd")];
                    }
                    else {
                        textfieldCell.textLabel.text = RichLocaleString(@"End Date");
                        textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
                        textfieldCell.textfield.inputView = endDatePicker;
                        textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:endDatePicker.date format:RichLocaleString(@"yyyy-MM-dd")];
                    }
                    
                    break;
                    
                case ByMonth:
                    if ([indexPath row] == 1) {
                        textfieldCell.textLabel.text = RichLocaleString(@"Begin Month");
                        textfieldCell.textfield.returnKeyType = UIReturnKeyNext;
                        textfieldCell.textfield.inputView = beginDatePicker;
                        textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:beginDatePicker.date format:RichLocaleString(@"yyyy-MM")];
                    }
                    else {
                        textfieldCell.textLabel.text = RichLocaleString(@"End Month");
                        textfieldCell.textfield.returnKeyType = UIReturnKeyDone;
                        textfieldCell.textfield.inputView = endDatePicker;
                        textfieldCell.textfield.text = [[RichDelegate core] stringFromDate:endDatePicker.date format:RichLocaleString(@"yyyy-MM")];
                    }
                    
                    break;
            }
        }
    }
    
    return cell;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }   
    else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

#pragma mark - Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Navigation logic may go here. Create and push another view controller.
    /*
     <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];
     // ...
     // Pass the selected object to the new view controller.
     [self.navigationController pushViewController:detailViewController animated:YES];
     [detailViewController release];
     */
    
    if (self.callerDelegate) {
        if ([tableView cellForRowAtIndexPath:indexPath].accessoryType == UITableViewCellAccessoryNone) {
            [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryCheckmark;
        }
        else {
            [tableView cellForRowAtIndexPath:indexPath].accessoryType = UITableViewCellAccessoryNone;
        }
        
        [self.callerDelegate tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath];
        return;
    }
    
    ExpendViewController *evc;
    IncomeViewController *ivc;
    TransferViewController *tvc;
    RichTransactionGeneral *transaction = nil;
    
    if ([queryTransactions count] > 0)
        transaction = [queryTransactions objectAtIndex:[indexPath row]];
    
    if (transaction) {
        switch (transaction.categoryCode & 0x000000ff) {
            case RootCategoryExpend:
                evc = [[ExpendViewController alloc] initWithStyle:UITableViewStylePlain];
                evc.transaction = transaction;
                evc.mode = RichTableModeUpdate;
                evc.navigator = self.navigator;
                [self.navigator pushViewController:evc animated:YES];
                [evc release];
                break;
                
            case RootCategoryIncome:
                ivc = [[IncomeViewController alloc] initWithStyle:UITableViewStylePlain];
                ivc.transaction = transaction;
                ivc.mode = RichTableModeUpdate;
                ivc.navigator = self.navigator;
                [self.navigator pushViewController:ivc animated:YES];
                [ivc release];
                break;
                
            case RootCategoryTransfer:
                tvc = [[TransferViewController alloc] initWithStyle:UITableViewStylePlain];
                tvc.transaction = transaction;
                tvc.mode = RichTableModeUpdate;
                tvc.navigator = self.navigator;
                [self.navigator pushViewController:tvc animated:YES];
                [tvc release];
                break;
        }
    }
}

#pragma mark - Picker view delegate and datasource

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)tableComponents
{
    [super pickerView:pickerView didSelectRow:row inComponent:tableComponents];
    
    dateCondition = (DateCondition)row;
    
    if (dateCondition == ByDay) {
        beginDatePicker.dateFormat = endDatePicker.dateFormat = RichLocaleString(@"Y-M-D");
    }
    else if (dateCondition == ByMonth) {
        beginDatePicker.dateFormat = endDatePicker.dateFormat = RichLocaleString(@"Y-M");
    }
    
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:1 inSection:0]] withRowAnimation:NO];
    [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:2 inSection:0]] withRowAnimation:NO];
}

#pragma mark - Toolbar button actions

- (void)loadSearchResult:(NSString *)condition
{
    [[RichDelegate core] loadGeneralTransactions:queryTransactions
                                        category:RootCategoryAll
                                           where:condition
                                    beginAtIndex:(self.page * ROWS_PER_PAGE)
                                           limit:ROWS_PER_PAGE
                                      descending:YES];
    
    if (self.mode == RichTableModeListReadonly)
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:0] withRowAnimation:UITableViewRowAnimationAutomatic];
    else
        [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationAutomatic];
}

- (void)toolbarDidPressNextButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 1) {
        if (dateCondition == ByDay) {
            beginDate = [beginDatePicker.date copy];
            beginDatePicker.date = beginDate;
            currentTextfield.text = [[RichDelegate core] stringFromDate:beginDate format:RichLocaleString(@"yyyy-MM-dd")];
        }
        else if (dateCondition == ByMonth) {
            beginDate = [[DateHelper firstDayOfMonthForDate:beginDatePicker.date] copy];
            beginDatePicker.date = beginDate;
            currentTextfield.text = [[RichDelegate core] stringFromDate:beginDate format:RichLocaleString(@"yyyy-MM")];
        }
        else
            return;
    }
    else if (currentTextfield.tag == 2) {
        if (dateCondition == ByDay) {
            endDate = [endDatePicker.date copy];
            endDatePicker.date = endDate;
            currentTextfield.text = [[RichDelegate core] stringFromDate:endDate format:RichLocaleString(@"yyyy-MM-dd")];
        }
        else if (dateCondition == ByMonth) {
            endDate = [[DateHelper lastDayOfMonthForDate:endDatePicker.date] copy];
            endDatePicker.date = endDate;
            currentTextfield.text = [[RichDelegate core] stringFromDate:endDate format:RichLocaleString(@"yyyy-MM")];
        }
        else
            return;
    }
    
    [self loadSearchResult:[self dateConditionString]];
    
    [super toolbarDidPressNextButton:sender];
}

- (void)toolbarDidPressDoneButton:(UIBarButtonItem *)sender
{
    if (currentTextfield.tag == 1) {
        if (dateCondition == ByDay) {
            beginDate = [beginDatePicker.date copy];
            beginDatePicker.date = beginDate;
            currentTextfield.text = [[RichDelegate core] stringFromDate:beginDate format:RichLocaleString(@"yyyy-MM-dd")];
        }
        else if (dateCondition == ByMonth) {
            beginDate = [[DateHelper firstDayOfMonthForDate:beginDatePicker.date] copy];
            beginDatePicker.date = beginDate;
            currentTextfield.text = [[RichDelegate core] stringFromDate:beginDate format:RichLocaleString(@"yyyy-MM")];
        }
        else
            return;
    }
    else if (currentTextfield.tag == 2) {
        if (dateCondition == ByDay) {
            endDate = [endDatePicker.date copy];
            endDatePicker.date = endDate;
            currentTextfield.text = [[RichDelegate core] stringFromDate:endDate format:RichLocaleString(@"yyyy-MM-dd")];
        }
        else if (dateCondition == ByMonth) {
            endDate = [[DateHelper lastDayOfMonthForDate:endDatePicker.date] copy];
            endDatePicker.date = endDate;
            currentTextfield.text = [[RichDelegate core] stringFromDate:endDate format:RichLocaleString(@"yyyy-MM")];
        }
        else
            return;
    }
    
    [self loadSearchResult:[self dateConditionString]];
    
    [super toolbarDidPressDoneButton:sender];
}

@end
